<template>
  <BasicModal v-bind="$attrs" :title="getTitle" @register="register" width="70%" @ok="handleSubmit">
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>

<script setup lang="ts">
  import { ref, computed } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { formSchemas } from '../resourceManagement.data';
  import { addResourceServe, editResourceServe, ResourceParam } from '/@/api/admin/resoure';
  import { cloneDeep } from 'lodash-es';
  import { useMessage } from '/@/hooks/web/useMessage';

  type UpdatedType = 'add' | 'edit';

  const emit = defineEmits(['register', 'success']);

  const { createMessage } = useMessage();

  const updated = ref<UpdatedType>('add');
  const [registerForm, { validate, setFieldsValue, resetFields }] = useForm({
    labelWidth: 120,
    showResetButton: false,
    showSubmitButton: false,
    schemas: formSchemas,
    baseColProps: {
      span: 12,
    },
  });
  let recordId = '';
  const [register, { changeLoading, setModalProps, closeModal }] = useModalInner((data) => {
    resetFields();
    updated.value = data.updated;
    if (data.updated === 'edit') {
      recordId = data.id;
      setFieldsValue({
        ...data,
        ...JSON.parse(data.data),
      });
    }
  });

  const getTitle = computed(() => (updated.value === 'add' ? '新增' : '编辑'));

  // 提交
  const handleSubmit = async () => {
    const values = await validate();
    changeLoading(true);
    setModalProps({
      confirmLoading: true,
    });
    const { classify, code, name, summary, ...data } = cloneDeep(values);
    let params: ResourceParam = {
      classify,
      code,
      name,
      summary,
      data: JSON.stringify({ ...data }),
    };

    let Api = addResourceServe;
    if (updated.value === 'edit') {
      Api = editResourceServe;
      params.id = recordId;
    }

    try {
      await Api(params);
      createMessage.success('操作成功');
      emit('success');
      closeModal();
    } catch (e: any) {
      console.log(e);
      throw e;
    } finally {
      changeLoading(false);
      setModalProps({
        confirmLoading: false,
      });
    }
  };
</script>

<style lang="less" scoped></style>
